// pages/mine/mine.js
const app = getApp();
import api from '../../api/index.js'
const { request } = require('../../utils/wx-api.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo:'',
    isLogin:false
  },
  toAddressManage(){
    if(!app.globalData.userInfo){
      wx.showToast({
        title: '请先登录',
        icon:'none'
      })
    }else{
      wx.navigateTo({
        url: '../addressManage/addressManage'
      })
    }
  },
  login(res){
    console.log('login',res);
    if (res.detail.errMsg.indexOf('fail') != -1) {
      //说明用户拒绝授权
      //请授权，否则相关功能不可用
      wx.showToast({
        icon: 'none',
        title: '请授权，否则相关功能不可用',
        duration: 3000
      })
    } else {
      let userInfoDetail = res.detail;
      let {userInfo} = res.detail;
      let that = this;
      wx.login({
        success: function (result) {
          // console.log('code',result);
          request({url: api.loginByWeixin},{
            appId: 'wxfa48bdefa8725047',
            secret: '00d987a912597db6c7651655bf722452',
            code: result.code,
            userInfo: userInfoDetail
          }, "POST")
          .then(res => {
            console.log(res);
            if (res.data.errmsg) {
              wx.showModal({
                title: '提示',
                content: '登录失败'
              })
            } else {
              app.globalData.userInfo = userInfo;
              wx.setStorageSync('token', res.data.data.token);
              app.globalData.token = wx.getStorageSync('token');
              // console.log("token", app.globalData.token);
              that.setData({
                userInfo: app.globalData.userInfo,
                isLogin:true
              })
              if(app.globalData.redirectUrl){
                wx.navigateTo({
                  url:`../detail/detail?id=${app.globalData.redirectUrl}`
                })
                app.globalData.redirect='';
                console.log('back',app);
              }
            }
          })
        }
      })
    }
  },
  mineOrder(){
    wx.navigateTo({
      url: '../orderList/orderList'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(app.globalData.userInfo){
      this.setData({
        userInfo:app.globalData.userInfo,
        isLogin:true
      })
    }else {
      this.setData({
        isLogin:false
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})